<script setup lang="ts">

import type {Ref} from "vue-demi";
import {addVneue, updateVneue, type VneueDto} from "@/apis/vneue";
import type {img} from "@/components/ImgUpload/index.vue";
import {uploadFile} from "@/utils/file";
import {useUserStore} from "@/stores";
import type {OssFileVo} from "@/apis/oss";
import {Message} from "@arco-design/web-vue";

const userInfo = useUserStore().userInfo

const visible = defineModel('visible', {
  type: Boolean,
  default: false
});

const img:Ref<img[]> = defineModel('img', {
  type: Array<img>,
  default: []
})

const dto:Ref<VneueDto> = defineModel('dto', {
  type: Object,
  default: {
    id: 0,
    description: '',
    history: '',
    ossId: '',
    updateBy: 1,
    updateTime: '',
    status: 1
  }
})

const emit = defineEmits(["ok"])

const selectImg = async (data: Ref<img[]>) => {
  let temp = data.value
  let tempLength = data.value.length
  for (let i = 0; i < tempLength;i++) {
    if (!temp[i].isNow) {
      continue
    }
    const res = await uploadFile(temp[i].file, userInfo.id, 'vneueImg')
    let resData = res.data.data as OssFileVo
    temp[i].id = resData.ossId
    temp[i].isNow = false
  }
  img.value = data.value
}

const delImg = (data: Ref<img[]>) => {
  img.value = data.value
}

const subForm = () => {

  for (let i = 0; i < img.value.length; i++) {
    dto.value.ossId += img.value[i].id + ","
  }

  dto.value.ossId.substring(dto.value.ossId.length - 1, dto.value.ossId.length)

  if (dto.value.id === 0) {
    addVneue(dto.value).then(res => {
      Message.success({
        content:"新增成功"
      })
      emit("ok")
      clearForm()
      visible.value = false
    })
  } else {
    //修改

    updateVneue(dto.value).then(res => {
      Message.success({
        content:"修改成功"
      })
      emit("ok")
      clearForm()
      visible.value = false
    })

  }


}

const cancelHandler = () => {
  clearForm()
  visible.value = false
}

const clearForm = () => {
  dto.value = {
    id: 0,
    description: '',
    history: '',
    ossId: '',
    updateBy: userInfo.id,
    updateTime: '',
    status: 1 + ""
  }
  img.value = []
}



</script>

<template>
<a-modal v-model:visible="visible" title="场景" @ok="subForm" @cancel="cancelHandler" >
  <a-form :model="dto">

    <a-form-item label="场景描述">
      <a-textarea v-model="dto.description" placeholder="请输入场景描述" :max-length="254" show-word-limit />
    </a-form-item>

    <a-form-item label="场景历史">
      <a-textarea v-model="dto.history" placeholder="请输入场景历史" />
    </a-form-item>

    <a-form-item label="场景图片">
      <img-upload @imgs="selectImg" @delImg="delImg" :src="img" />
    </a-form-item>

  </a-form>
</a-modal>
</template>

<style scoped lang="scss">

</style>